<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\lawyer\controller;

use app\base\BaseController;
use app\lawyer\model\Lawyer as LawyerList;
use app\lawyer\validate\LawyerCheck;
use avatars\MDAvatars;
use Overtrue\Pinyin\Pinyin;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Lawyer extends BaseController
{
    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = $this->buildWhereClause($param);

            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];

            $layer = LawyerList::where($where)
                ->order('id desc')
                ->paginate(['list_rows' => $rows])
                ->each(function ($item, $key) {
                    $item->lawfirm = Db::name('Lawfirm')->where(['id' => $item->firmid])->value('title');
                    $item->province = Db::name('region')->where(['id' => $item->provinceid])->value('name');
                    $item->city = Db::name('region')->where(['id' => $item->cityid])->value('name');
                    $item->entry_time = empty($item->entry_time) ? '-' : date('Y-m-d', $item->entry_time);
                    $item->last_login_time = empty($item->last_login_time) ? '-' : date('Y-m-d H:i', $item->last_login_time);
                    $item->last_login_ip = empty($item->last_login_ip) ? '-' : $item->last_login_ip;
                });

            return table_assign(0, '', $layer);
        } else {
            return view();
        }
    }

    /**
     * 构建查询条件
     * @param array $param 请求参数
     * @return array 查询条件数组
     */
    private function buildWhereClause(array $param): array
    {
        $where = [];
        if (!empty($param['keywords'])) {
            $where[] = ['name|mobile', 'like', '%' . $param['keywords'] . '%'];
        }
        if (isset($param['status']) && $param['status']!='') {
            $where[] = ['status', '=', $param['status']];
        } else {
            $where[] = ['status', '<', 2];
        }
        if (!empty($param['type'])) {
            $where[] = ['type', '=', $param['type']];
        }
        return $where;
    }

    // 生成唯一用户名
    private function generateUniqueUsername($username, $id = 0)
    {
        // 确保原始用户名长度在 4 到 20 位之间
        if (strlen($username) < 4) {
            $username = str_pad($username, 4, '0', STR_PAD_RIGHT);
        } elseif (strlen($username) > 20) {
            $username = substr($username, 0, 20);
        }
    
        $count = Db::name('Lawyer')->where([['username', 'like', $username.'%']])->count();
        if ($count > 0) {
            $i = 1;
            while (true) {
                $newUsername = $username . $i;
                // 确保新生成的用户名长度在 4 到 20 位之间
                if (strlen($newUsername) > 20) {
                    $newUsername = substr($newUsername, 0, 20);
                }
                $checkCount = Db::name('Lawyer')->where([['username', '=', $newUsername], ['id', '<>', $id], ['status', '>=', 0]])->count();
                if ($checkCount === 0) {
                    return $newUsername;
                }
                $i++;
            }
        }
        return $username;
    }

    // 添加或编辑律师信息
    public function add()
    {
        $param = get_params();
        // Convert the id parameter to an integer
        $id = isset($param['id']) ? (int)$param['id'] : 0;
        
        if (request()->isAjax()) {
            $param['entry_time'] = strtotime($param['entry_time']);
            $param['nickname'] = $param['name'];

            // 仅在新增时生成用户名
            if ($id === 0) {
                $username = Pinyin::name($param['name'],'none')->join('');
                $param['username'] = $this->generateUniqueUsername($username, $id);
            }
            // 处理添加或编辑操作
            if ($id > 0) {
                $this->handleEdit($param);
            } else {
                $this->handleAdd($param);
            }
        
            return to_assign();
        } else {
            $this->initViewData($id);
            return view();
        }
    }

    // 处理编辑操作
    private function handleEdit(array $param)
    {
        // 检查 username 字段是否存在
        if (!isset($param['username'])) {
            // 如果不存在，可以从数据库中获取当前的 username
            $currentLawyer = Db::name('Lawyer')->where('id', $param['id'])->find();
            $param['username'] = $currentLawyer['username'] ?? '';
        }
    
        $count = Db::name('Lawyer')->where([['username', '=', $param['username']], ['id', '<>', $param['id']], ['status', '>=', 0]])->count();
        if ($count > 0) {
            $param['username'] = $this->generateUniqueUsername($param['username'], $param['id']);
        }
    
        try {
            validate(LawyerCheck::class)->scene('edit')->check($param);
        } catch (ValidateException $e) {
            return to_assign(1, $e->getError());
        }
    
        $this->executeTransaction(function () use ($param) {
            Db::name('Lawyer')->where(['id' => $param['id']])->strict(false)->field(true)->update($param);
            $this->setAvatarIfNeeded((int)$param['id'], $param['name']);
            add_log('edit', $param['id'], $param);
            clear_cache('adminMenu');
        });
    }

    // 处理添加操作
    private function handleAdd(array $param)
    {
        try {
            validate(LawyerCheck::class)->scene('add')->check($param);
        } catch (ValidateException $e) {
            return to_assign(1, $e->getError());
        }

        $param['salt'] = set_salt(20);
        $param['pwd'] = set_password($param['reg_pwd'], $param['salt']);

        $this->executeTransaction(function () use ($param) {
            $uid = Db::name('Lawyer')->strict(false)->field(true)->insertGetId($param);
            $this->setAvatarIfNeeded($uid, $param['name']);
            add_log('add', $uid, $param);
        });
    }

    // 初始化视图数据
    private function initViewData(int $id)
    {
        $firm = get_lawfirm();

        if ($id > 0) {
            $detail = get_lawyer($id);
        } else {
            $reg_pwd = '123456';
            View::assign('reg_pwd', $reg_pwd);
            $detail['provinceid'] = 0;
            $detail['cityid'] = 0;
        }

        View::assign('detail', $detail);
        View::assign('firm', $firm);
        View::assign('id', $id);
    }

    // 执行事务
    private function executeTransaction(callable $callback)
    {
        Db::startTrans();
        try {
            $callback();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return to_assign(1, '提交失败:' . $e->getMessage());
        }
    }

    // 如果头像为空，则生成头像
    private function setAvatarIfNeeded(int $id, string $name)
    {
        $param = Db::name('Lawyer')->where('id', $id)->find();
        if (!isset($param['thumb']) || $param['thumb'] == '') {
            $char = mb_substr($name, 0, 1, 'utf-8');
            Db::name('Lawyer')->where('id', $id)->update(['thumb' => $this->to_avatars($char)]);
        }
    }

    // 生成头像
    public function to_avatars($char)
    {
        $defaultData = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'S', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '拾',
            '一', '二', '三', '四', '五', '六', '七', '八', '九', '十');
        $Char = isset($char) ? $char : $defaultData[mt_rand(0, count($defaultData) - 1)];
        $OutputSize = min(512, empty($_GET['size']) ? 36 : intval($_GET['size']));

        $Avatar = new MDAvatars($Char, 256, 1);
        $avatar_name = '/avatars/avatar_256_' . set_salt(10) . time() . '.png';
        $path = get_config('filesystem.disks.public.url') . $avatar_name;
        $res = $Avatar->Save('.' . $path, 256);
        $Avatar->Free();
        return $path;
    }

    // 查看律师信息
    public function view()
    {
        $id = get_params('id');
        $detail = get_lawyer($id);
        $menu = Db::name('AdminRule')->where(['menu' => 1])->order('sort asc,id asc')->select()->toArray();
        $rule = Db::name('AdminRule')->order('sort asc,id asc')->select()->toArray();
        $province = Db::name('region')->where('id', $detail['provinceid'])->value('name');
        $city = Db::name('region')->where('id', $detail['cityid'])->value('name');
        $detail['provinceName'] = $province;
        $detail['cityName'] = $city;

        View::assign('detail', $detail);
        add_log('view', get_params('id'));
        return view();
    }

    // 禁用或恢复律师账号
    public function set()
    {
        $type = get_params("type");
        $ids = get_params("ids");
        $idArray = explode(',', $ids);
        $list = [];

        foreach ($idArray as $val) {
            if ($val == 1) {
                continue;
            }
            $list[] = [
                'status' => $type,
                'id' => $val,
                'update_time' => time(),
            ];
        }

        foreach ($list as $v) {
            if (Db::name('Lawyer')->update($v) !== false) {
                if ($type == 0) {
                    add_log('disable', $v['id']);
                } else if ($type == 1) {
                    add_log('recovery', $v['id']);
                }
            }
        }

        return to_assign(0, '操作成功');
    }

    // 重置律师密码
    public function reset_psw()
    {
        $id = get_params("id");
        if ($id == 1) {
            return to_assign(1, '该账号是超级管理员，不允许重置');
        }

        $new_pwd = set_salt(6);
        $salt = set_salt(20);
        $data = [
            'reg_pwd' => $new_pwd,
            'salt' => $salt,
            'pwd' => set_password($new_pwd, $salt),
            'id' => $id,
            'update_time' => time(),
        ];

        if (Db::name('Lawyer')->update($data) !== false) {
            add_log('reset', $id);
            return to_assign(0, '操作成功');
        } else {
            return to_assign(1, '操作失败');
        }
    }

    // 管理员操作日志
    public function log()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = $this->buildLogWhereClause($param);

            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $content = DB::name('AdminLog')
                ->field("id,uid,name,action,title,content,rule_menu,ip,param_id,param,FROM_UNIXTIME(create_time,'%Y-%m-%d %H:%i:%s') create_time")
                ->order('create_time desc')
                ->where($where)
                ->paginate($rows, false, ['query' => $param]);

            $content->toArray();
            foreach ($content as $k => $v) {
                $data = $v;
                $param_array = json_decode($v['param'], true);
                $param_value = '';
                foreach ($param_array as $key => $value) {
                    if (is_array($value)) {
                        $value = implode(',', $value);
                    }
                    $param_value .= $key . ':' . $value . '&nbsp;&nbsp;|&nbsp;&nbsp;';
                }
                $data['param'] = $param_value;
                $content->offsetSet($k, $data);
            }

            return table_assign(0, '', $content);
        } else {
            return view();
        }
    }

    /**
     * 构建日志查询条件
     * @param array $param 请求参数
     * @return array 查询条件数组
     */
    private function buildLogWhereClause(array $param): array
    {
        $where = [];
        if (!empty($param['keywords'])) {
            $where[] = ['name|rule_menu|param_id', 'like', '%' . $param['keywords'] . '%'];
        }
        if (!empty($param['title_cate'])) {
            $where['title'] = $param['title_cate'];
        }
        if (!empty($param['rule_menu'])) {
            $where['rule_menu'] = $param['rule_menu'];
        }
        return $where;
    }
}
